/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.bussiness.exam.paper.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.seeyoui.kensite.bussiness.exam.common.Const;
import com.seeyoui.kensite.bussiness.exam.paper.domain.Paper;
import com.seeyoui.kensite.bussiness.exam.paper.service.PaperService;
import com.seeyoui.kensite.bussiness.exam.paperQuestion.domain.PaperQuestion;
import com.seeyoui.kensite.bussiness.exam.paperQuestion.service.PaperQuestionService;
import com.seeyoui.kensite.bussiness.exam.question.domain.Question;
import com.seeyoui.kensite.bussiness.exam.question.service.QuestionService;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.excel.ExportExcel;
/**
 * Paper
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-01-08
 */

@Controller
@RequestMapping(value = "exam/paper")
public class PaperController extends BaseController {
	
	@Autowired
	private PaperService paperService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private PaperQuestionService paperQuestionService;
	
	/**
	 * 展示列表页面
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:view")
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("bussiness/exam/paper/"+page, modelMap);
	}
	
	/**
	 * 根据ID查询单条数据
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:select")
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String id) throws Exception {
		Paper paper = paperService.findOne(id);
		return paper;
	}
	
	/**
	 * 根据ID查询单条数据并返回相应表单
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:view")
	@RequestMapping(value = "/form/{page}/{id}")
	public ModelAndView form(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page, @PathVariable String id) throws Exception {
		Paper paper = paperService.findOne(id);
		modelMap.put("paper", paper);
		return new ModelAndView("bussiness/exam/paper/"+page, modelMap);
	}
	
	/**
	 * 获取列表展示数据
	 * @param modelMap
	 * @param paper
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:select")
	@RequestMapping(value = "/list/data", method=RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Paper paper) throws Exception {
		List<Paper> paperList = paperService.findList(paper);
		int total = paperService.findTotal(paper);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(paperList);
		return eudg;
	}
	
	/**
	 * 获取列表展示数据带分页器用于jsp自己做分页
	 * @param modelMap
	 * @param paper
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:view")
	@RequestMapping(value = "/list/page", method=RequestMethod.POST)
	@ResponseBody
	public Object listPage(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Paper paper) throws Exception {
		List<Paper> paperList = paperService.findList(paper);
		int total = paperService.findTotal(paper);
		Page<Paper> page = new Page<Paper>(paper.getPage(), paper.getRows(), total);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("rows", paperList);
		dataMap.put("page", page);
		return dataMap;
	}
	
	/**
	 * 获取所有数据
	 * @param modelMap
	 * @param paper
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:select")
	@RequestMapping(value = "/list/all", method=RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Paper paper) throws Exception {
		List<Paper> paperList = paperService.findAll(paper);
		return paperList;
	}
	
	/**
	 * 保存新增的数据
	 * @param modelMap
	 * @param paper
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:insert")
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	@ResponseBody
	public String save(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Paper paper) throws Exception {
		if (!beanValidator(modelMap, paper)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		
		// 先保存试卷，确保该试卷有ID
		String string = paperService.save(paper);
		
		Map<String, Integer> mapQuestionId2Count = new HashMap<>();
		// 单选题
		mapQuestionId2Count.put(Const.QUESTION_TYPE_ID_SINGLE, Integer.parseInt(paper.getSingleCount()));
		// 多选题
		mapQuestionId2Count.put(Const.QUESTION_TYPE_ID_MULTIPLE, Integer.parseInt(paper.getMultipleCount()));
		// 判断题
		mapQuestionId2Count.put(Const.QUESTION_TYPE_ID_JUDGE, Integer.parseInt(paper.getJudgeCount()));
		
		// 开始为该试卷随机抽取试题
		for (Entry<String, Integer> entry : mapQuestionId2Count.entrySet()) {
			if(entry.getValue() <= 0) {
				continue;
			}
			Question questionQry = new Question();
			questionQry.setLibraryId(paper.getLibraryId());
			questionQry.setQuestionTypeId(entry.getKey());
			// 查询该试题类型的在指定题库中的全部试题
			List<Question> lsQuestions = questionService.findList(questionQry);
			
			Set<String> setQuestionIds = new HashSet<>();
			int index = 0;
			Question question = null;
			while (setQuestionIds.size() < entry.getValue() && setQuestionIds.size() < lsQuestions.size()) {
				// 向setQuestionIds中随机添加试题ID
				index = (int) (Math.random()*lsQuestions.size());
				question = lsQuestions.get(index);
				setQuestionIds.add(question.getId());
			}
			
			// 将随机选取的试题写入数据库中
			for (String questionId : setQuestionIds) {
				PaperQuestion paperQuestion = new PaperQuestion();
				paperQuestion.setQuestionId(questionId);
				paperQuestion.setPaperId(string);
				paperQuestionService.save(paperQuestion);
			}
		}
		
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 保存修改的数据
	 * @param modelMap
	 * @param paper
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:update")
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Paper paper) throws Exception {
		if (!beanValidator(modelMap, paper)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		paperService.update(paper);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 删除数据库
	 * @param modelMap
	 * @param paperId
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:delete")
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		paperService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 假删除
	 * @param modelMap
	 * @param paper
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:delete")
	@RequestMapping(value = "/remove", method=RequestMethod.POST)
	@ResponseBody
	public String remove(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Paper paper) throws Exception {
		paperService.remove(paper);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 导出Excel数据
	 * @param modelMap
	 * @param paper
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:paper:export")
	@RequestMapping(value = "/export")
	public String export(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Paper paper) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<Paper> paperList = paperService.findAll(paper);
		new ExportExcel(null, Paper.class).setDataList(paperList).write(response, fileName).dispose();
		return null;
	}
}